<template>
  <div class="import-export">
    <div class="page-header">
      <h1>数据导入导出</h1>
      <p>管理系统数据的批量导入和导出操作</p>
    </div>

    <el-row :gutter="20">
      <!-- 导入功能 -->
      <el-col :span="12">
        <el-card class="import-card">
          <template #header>
            <div class="card-header">
              <h3>
                <el-icon><Upload /></el-icon>
                数据导入
              </h3>
            </div>
          </template>

          <el-tabs v-model="importTab" type="border-card">
            <!-- 用户导入 -->
            <el-tab-pane label="用户导入" name="users">
              <div class="import-content">
                <el-alert
                  title="导入说明"
                  description="支持批量导入用户信息，请按照模板格式准备Excel文件。系统将自动创建用户账号并发送邮件通知。"
                  type="info"
                  :closable="false"
                />

                <div class="upload-area">
                  <el-upload
                    class="upload-demo"
                    drag
                    :auto-upload="false"
                    :on-change="handleUserFileChange"
                    :limit="1"
                    accept=".xlsx,.xls,.csv"
                  >
                    <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
                    <div class="el-upload__text">
                      将文件拖到此处，或<em>点击上传</em>
                    </div>
                    <template #tip>
                      <div class="el-upload__tip">
                        支持 xlsx/xls/csv 文件，不超过 10MB
                      </div>
                    </template>
                  </el-upload>
                </div>

                <div class="import-options">
                  <el-form label-width="120px" size="small">
                    <el-form-item label="重复处理">
                      <el-radio-group v-model="userImportOptions.duplicateHandling">
                        <el-radio value="skip">跳过重复用户</el-radio>
                        <el-radio value="update">更新现有用户</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="发送通知">
                      <el-switch v-model="userImportOptions.sendNotification" />
                    </el-form-item>
                    <el-form-item label="默认密码">
                      <el-input
                        v-model="userImportOptions.defaultPassword"
                        placeholder="不填写则使用随机密码"
                        style="width: 200px"
                      />
                    </el-form-item>
                  </el-form>
                </div>

                <div class="action-buttons">
                  <el-button @click="downloadUserTemplate">
                    <el-icon><Download /></el-icon>
                    下载模板
                  </el-button>
                  <el-button
                    type="primary"
                    @click="importUsers"
                    :loading="importing.users"
                    :disabled="!userImportFile"
                  >
                    开始导入
                  </el-button>
                </div>
              </div>
            </el-tab-pane>

            <!-- 题目导入 -->
            <el-tab-pane label="题目导入" name="questions">
              <div class="import-content">
                <el-alert
                  title="导入说明"
                  description="支持批量导入题目到指定题库，支持多种题型格式。请确保题目格式符合模板要求。"
                  type="info"
                  :closable="false"
                />

                <div class="upload-area">
                  <el-upload
                    class="upload-demo"
                    drag
                    :auto-upload="false"
                    :on-change="handleQuestionFileChange"
                    :limit="1"
                    accept=".xlsx,.xls,.csv,.json"
                  >
                    <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
                    <div class="el-upload__text">
                      将文件拖到此处，或<em>点击上传</em>
                    </div>
                    <template #tip>
                      <div class="el-upload__tip">
                        支持 xlsx/xls/csv/json 文件，不超过 20MB
                      </div>
                    </template>
                  </el-upload>
                </div>

                <div class="import-options">
                  <el-form label-width="120px" size="small">
                    <el-form-item label="目标题库">
                      <el-select v-model="questionImportOptions.questionBankId" style="width: 200px">
                        <el-option
                          v-for="bank in questionBanks"
                          :key="bank.id"
                          :label="bank.name"
                          :value="bank.id"
                        />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="重复处理">
                      <el-radio-group v-model="questionImportOptions.duplicateHandling">
                        <el-radio value="skip">跳过重复题目</el-radio>
                        <el-radio value="update">更新现有题目</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="自动分类">
                      <el-switch v-model="questionImportOptions.autoCategory" />
                    </el-form-item>
                  </el-form>
                </div>

                <div class="action-buttons">
                  <el-button @click="downloadQuestionTemplate">
                    <el-icon><Download /></el-icon>
                    下载模板
                  </el-button>
                  <el-button
                    type="primary"
                    @click="importQuestions"
                    :loading="importing.questions"
                    :disabled="!questionImportFile"
                  >
                    开始导入
                  </el-button>
                </div>
              </div>
            </el-tab-pane>

            <!-- 成绩导入 -->
            <el-tab-pane label="成绩导入" name="grades">
              <div class="import-content">
                <el-alert
                  title="导入说明"
                  description="支持批量导入考试成绩，需要关联到对应的考试和学生。系统将自动计算总分和及格状态。"
                  type="info"
                  :closable="false"
                />

                <div class="upload-area">
                  <el-upload
                    class="upload-demo"
                    drag
                    :auto-upload="false"
                    :on-change="handleGradeFileChange"
                    :limit="1"
                    accept=".xlsx,.xls,.csv"
                  >
                    <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
                    <div class="el-upload__text">
                      将文件拖到此处，或<em>点击上传</em>
                    </div>
                    <template #tip>
                      <div class="el-upload__tip">
                        支持 xlsx/xls/csv 文件，不超过 10MB
                      </div>
                    </template>
                  </el-upload>
                </div>

                <div class="import-options">
                  <el-form label-width="120px" size="small">
                    <el-form-item label="关联考试">
                      <el-select v-model="gradeImportOptions.examinationId" style="width: 200px">
                        <el-option
                          v-for="exam in examinations"
                          :key="exam.id"
                          :label="exam.title"
                          :value="exam.id"
                        />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="覆盖已有成绩">
                      <el-switch v-model="gradeImportOptions.overwriteExisting" />
                    </el-form-item>
                    <el-form-item label="自动发布">
                      <el-switch v-model="gradeImportOptions.autoPublish" />
                    </el-form-item>
                  </el-form>
                </div>

                <div class="action-buttons">
                  <el-button @click="downloadGradeTemplate">
                    <el-icon><Download /></el-icon>
                    下载模板
                  </el-button>
                  <el-button
                    type="primary"
                    @click="importGrades"
                    :loading="importing.grades"
                    :disabled="!gradeImportFile"
                  >
                    开始导入
                  </el-button>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>

      <!-- 导出功能 -->
      <el-col :span="12">
        <el-card class="export-card">
          <template #header>
            <div class="card-header">
              <h3>
                <el-icon><Download /></el-icon>
                数据导出
              </h3>
            </div>
          </template>

          <el-tabs v-model="exportTab" type="border-card">
            <!-- 用户导出 -->
            <el-tab-pane label="用户导出" name="users">
              <div class="export-content">
                <el-form label-width="100px" size="default">
                  <el-form-item label="导出范围">
                    <el-radio-group v-model="userExportOptions.scope">
                      <el-radio value="all">所有用户</el-radio>
                      <el-radio value="filtered">筛选结果</el-radio>
                      <el-radio value="selected">指定用户</el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <el-form-item v-if="userExportOptions.scope === 'filtered'" label="筛选条件">
                    <el-form :model="userExportOptions.filters" inline>
                      <el-form-item label="角色">
                        <el-select v-model="userExportOptions.filters.role" style="width: 120px">
                          <el-option label="全部" value="" />
                          <el-option label="管理员" value="admin" />
                          <el-option label="教师" value="teacher" />
                          <el-option label="学生" value="student" />
                        </el-select>
                      </el-form-item>
                      <el-form-item label="状态">
                        <el-select v-model="userExportOptions.filters.is_active" style="width: 100px">
                          <el-option label="全部" value="" />
                          <el-option label="启用" :value="true" />
                          <el-option label="禁用" :value="false" />
                        </el-select>
                      </el-form-item>
                    </el-form>
                  </el-form-item>

                  <el-form-item label="导出格式">
                    <el-radio-group v-model="userExportOptions.format">
                      <el-radio value="excel">Excel</el-radio>
                      <el-radio value="csv">CSV</el-radio>
                      <el-radio value="pdf">PDF</el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <el-form-item label="包含字段">
                    <el-checkbox-group v-model="userExportOptions.fields">
                      <el-checkbox value="basic">基本信息</el-checkbox>
                      <el-checkbox value="contact">联系方式</el-checkbox>
                      <el-checkbox value="academic">学术信息</el-checkbox>
                      <el-checkbox value="activity">活动记录</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                </el-form>

                <div class="action-buttons">
                  <el-button
                    type="primary"
                    @click="exportUsers"
                    :loading="exporting.users"
                  >
                    <el-icon><Download /></el-icon>
                    导出用户
                  </el-button>
                </div>
              </div>
            </el-tab-pane>

            <!-- 题目导出 -->
            <el-tab-pane label="题目导出" name="questions">
              <div class="export-content">
                <el-form label-width="100px" size="default">
                  <el-form-item label="题库来源">
                    <el-select v-model="questionExportOptions.questionBankId" style="width: 200px">
                  <el-option label="所有题库" :value="null" />
                  <el-option
                    v-for="bank in questionBanks"
                    :key="bank.id"
                    :label="bank.name"
                    :value="bank.id"
                  />
                </el-select>
                  </el-form-item>

                  <el-form-item label="题目类型">
                    <el-checkbox-group v-model="questionExportOptions.questionTypes">
                      <el-checkbox value="single_choice">单选题</el-checkbox>
                      <el-checkbox value="multiple_choice">多选题</el-checkbox>
                      <el-checkbox value="true_false">判断题</el-checkbox>
                      <el-checkbox value="fill_blank">填空题</el-checkbox>
                      <el-checkbox value="short_answer">简答题</el-checkbox>
                      <el-checkbox value="essay">论述题</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>

                  <el-form-item label="难度筛选">
                    <el-checkbox-group v-model="questionExportOptions.difficulties">
                      <el-checkbox value="easy">简单</el-checkbox>
                      <el-checkbox value="medium">中等</el-checkbox>
                      <el-checkbox value="hard">困难</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>

                  <el-form-item label="导出格式">
                    <el-radio-group v-model="questionExportOptions.format">
                      <el-radio value="excel">Excel</el-radio>
                      <el-radio value="json">JSON</el-radio>
                      <el-radio value="xml">XML</el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <el-form-item label="包含内容">
                    <el-checkbox-group v-model="questionExportOptions.includeContent">
                      <el-checkbox value="answers">答案</el-checkbox>
                      <el-checkbox value="analysis">解析</el-checkbox>
                      <el-checkbox value="tags">标签</el-checkbox>
                      <el-checkbox value="statistics">统计</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                </el-form>

                <div class="action-buttons">
                  <el-button
                    type="primary"
                    @click="exportQuestions"
                    :loading="exporting.questions"
                  >
                    <el-icon><Download /></el-icon>
                    导出题目
                  </el-button>
                </div>
              </div>
            </el-tab-pane>

            <!-- 成绩导出 -->
            <el-tab-pane label="成绩导出" name="grades">
              <div class="export-content">
                <el-form label-width="100px" size="default">
                  <el-form-item label="考试范围">
                    <el-select v-model="gradeExportOptions.examinationId" style="width: 200px">
                      <el-option label="所有考试" :value="null" />
                      <el-option
                        v-for="exam in examinations"
                        :key="exam.id"
                        :label="exam.title"
                        :value="exam.id"
                      />
                    </el-select>
                  </el-form-item>

                  <el-form-item label="班级筛选">
                    <el-select v-model="gradeExportOptions.classId" style="width: 150px">
                      <el-option label="所有班级" :value="null" />
                      <el-option
                        v-for="cls in classes"
                        :key="cls.id"
                        :label="cls.name"
                        :value="cls.id"
                      />
                    </el-select>
                  </el-form-item>

                  <el-form-item label="时间范围">
                    <el-date-picker
                      v-model="gradeExportOptions.dateRange"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      style="width: 220px"
                    />
                  </el-form-item>

                  <el-form-item label="导出格式">
                    <el-radio-group v-model="gradeExportOptions.format">
                      <el-radio value="excel">Excel</el-radio>
                      <el-radio value="pdf">PDF报告</el-radio>
                      <el-radio value="csv">CSV</el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <el-form-item label="报告类型">
                    <el-checkbox-group v-model="gradeExportOptions.reportTypes">
                      <el-checkbox value="scores">成绩单</el-checkbox>
                      <el-checkbox value="statistics">统计分析</el-checkbox>
                      <el-checkbox value="comparison">对比分析</el-checkbox>
                      <el-checkbox value="distribution">成绩分布</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                </el-form>

                <div class="action-buttons">
                  <el-button
                    type="primary"
                    @click="exportGrades"
                    :loading="exporting.grades"
                  >
                    <el-icon><Download /></el-icon>
                    导出成绩
                  </el-button>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>

    <!-- 导入结果对话框 -->
    <el-dialog
      v-model="showImportResult"
      title="导入结果"
      width="600px"
    >
      <div class="import-result">
        <el-result
          :icon="importResult.successCount > 0 ? 'success' : 'error'"
          :title="importResult.title"
          :sub-title="importResult.message"
        >
          <template #extra>
            <div class="result-stats">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="总记录数">{{ importResult.total }}</el-descriptions-item>
                <el-descriptions-item label="成功导入">{{ importResult.successCount }}</el-descriptions-item>
                <el-descriptions-item label="失败记录">{{ importResult.failCount }}</el-descriptions-item>
                <el-descriptions-item label="跳过记录">{{ importResult.skipCount }}</el-descriptions-item>
              </el-descriptions>
            </div>

            <div v-if="importResult.errors.length > 0" class="error-details">
              <h4>错误详情</h4>
              <el-table :data="importResult.errors" max-height="200">
                <el-table-column label="行号" prop="row" width="80" />
                <el-table-column label="错误信息" prop="error" />
              </el-table>
            </div>
          </template>
        </el-result>
      </div>
      <template #footer>
        <el-button @click="showImportResult = false">关闭</el-button>
        <el-button v-if="importResult.failCount > 0" type="primary" @click="downloadErrorLog">
          下载错误日志
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Upload,
  Download,
  UploadFilled
} from '@element-plus/icons-vue'
import { userApi, questionApi, gradingApi, examApi } from '@/api'

// 响应式数据
const importTab = ref('users')
const exportTab = ref('users')

// 基础数据
const questionBanks = ref<any[]>([])
const examinations = ref<any[]>([])
const classes = ref<any[]>([])

// 文件状态
const userImportFile = ref<File | null>(null)
const questionImportFile = ref<File | null>(null)
const gradeImportFile = ref<File | null>(null)

// 导入状态
const importing = reactive({
  users: false,
  questions: false,
  grades: false
})

// 导出状态
const exporting = reactive({
  users: false,
  questions: false,
  grades: false
})

// 导入选项
const userImportOptions = reactive({
  duplicateHandling: 'skip',
  sendNotification: true,
  defaultPassword: ''
})

const questionImportOptions = reactive({
  questionBankId: null as number | null,
  duplicateHandling: 'skip',
  autoCategory: true
})

const gradeImportOptions = reactive({
  examinationId: null as number | null,
  overwriteExisting: false,
  autoPublish: false
})

// 导出选项
const userExportOptions = reactive({
  scope: 'all',
  filters: {
    role: '',
    is_active: ''
  },
  format: 'excel',
  fields: ['basic', 'contact']
})

const questionExportOptions = reactive({
  questionBankId: null as number | null,
  questionTypes: ['single_choice', 'multiple_choice'],
  difficulties: ['easy', 'medium', 'hard'],
  format: 'excel',
  includeContent: ['answers', 'tags']
})

const gradeExportOptions = reactive({
  examinationId: null as number | null,
  classId: null as number | null,
  dateRange: null as [Date, Date] | null,
  format: 'excel',
  reportTypes: ['scores', 'statistics']
})

// 导入结果
const showImportResult = ref(false)
const importResult = reactive({
  title: '',
  message: '',
  total: 0,
  successCount: 0,
  failCount: 0,
  skipCount: 0,
  errors: [] as Array<{ row: number; error: string }>
})

// 获取基础数据
const fetchBaseData = async () => {
  try {
    const [bankResponse, examResponse, classResponse] = await Promise.all([
      questionApi.getQuestionBanks({ page_size: 1000 }),
      examApi.getExaminations({ page_size: 1000 }),
      userApi.getClasses({ page_size: 1000 })
    ])

    if (bankResponse.data?.results) {
      questionBanks.value = bankResponse.data.results
    }

    if (examResponse.data?.results) {
      examinations.value = examResponse.data.results
    }

    if (classResponse.data?.results) {
      classes.value = classResponse.data.results
    }
  } catch (error) {
    console.error('获取基础数据失败:', error)
  }
}

// 文件处理
const handleUserFileChange = (file: any) => {
  userImportFile.value = file.raw
}

const handleQuestionFileChange = (file: any) => {
  questionImportFile.value = file.raw
}

const handleGradeFileChange = (file: any) => {
  gradeImportFile.value = file.raw
}

// 用户导入
const importUsers = async () => {
  if (!userImportFile.value) {
    ElMessage.warning('请选择要导入的文件')
    return
  }

  importing.users = true
  try {
    const response = await userApi.importUsers(userImportFile.value)
    if (response.data) {
      showImportResult.value = true
      Object.assign(importResult, {
        title: '用户导入完成',
        message: `成功导入 ${response.data.imported} 个用户`,
        total: response.data.imported + response.data.skipped + response.data.errors?.length || 0,
        successCount: response.data.imported,
        skipCount: response.data.skipped,
        failCount: response.data.errors?.length || 0,
        errors: response.data.errors?.map((error: string, index: number) => ({
          row: index + 1,
          error
        })) || []
      })
    }

    userImportFile.value = null
  } catch (error) {
    console.error('用户导入失败:', error)
    ElMessage.error('用户导入失败')
  } finally {
    importing.users = false
  }
}

// 题目导入
const importQuestions = async () => {
  if (!questionImportFile.value || !questionImportOptions.questionBankId) {
    ElMessage.warning('请选择文件和目标题库')
    return
  }

  importing.questions = true
  try {
    const response = await questionApi.batchImportQuestions(
      questionImportOptions.questionBankId,
      { questions: [] } // 这里应该解析文件内容
    )

    if (response.data) {
      showImportResult.value = true
      Object.assign(importResult, {
        title: '题目导入完成',
        message: `成功导入 ${response.data.imported} 道题目`,
        total: response.data.imported + response.data.skipped + response.data.errors?.length || 0,
        successCount: response.data.imported,
        skipCount: response.data.skipped,
        failCount: response.data.errors?.length || 0,
        errors: response.data.errors?.map((error: string, index: number) => ({
          row: index + 1,
          error
        })) || []
      })
    }

    questionImportFile.value = null
  } catch (error) {
    console.error('题目导入失败:', error)
    ElMessage.error('题目导入失败')
  } finally {
    importing.questions = false
  }
}

// 成绩导入
const importGrades = async () => {
  if (!gradeImportFile.value || !gradeImportOptions.examinationId) {
    ElMessage.warning('请选择文件和关联考试')
    return
  }

  importing.grades = true
  try {
    // TODO: 实现成绩导入逻辑
    await new Promise(resolve => setTimeout(resolve, 2000))

    showImportResult.value = true
    Object.assign(importResult, {
      title: '成绩导入完成',
      message: '成绩导入成功',
      total: 10,
      successCount: 8,
      skipCount: 1,
      failCount: 1,
      errors: [{ row: 5, error: '学生不存在' }]
    })

    gradeImportFile.value = null
  } catch (error) {
    console.error('成绩导入失败:', error)
    ElMessage.error('成绩导入失败')
  } finally {
    importing.grades = false
  }
}

// 导出功能
const exportUsers = async () => {
  exporting.users = true
  try {
    await userApi.exportUsers({
      format: userExportOptions.format as 'excel' | 'csv' | 'pdf',
      role: userExportOptions.filters.role || undefined,
      is_active: userExportOptions.filters.is_active || undefined
    })
    ElMessage.success('用户数据导出成功')
  } catch (error) {
    console.error('用户导出失败:', error)
    ElMessage.error('用户导出失败')
  } finally {
    exporting.users = false
  }
}

const exportQuestions = async () => {
  if (!questionExportOptions.questionBankId) {
    ElMessage.warning('请选择题库')
    return
  }

  exporting.questions = true
  try {
    // TODO: 实现题目导出逻辑
    await new Promise(resolve => setTimeout(resolve, 2000))
    ElMessage.success('题目数据导出成功')
  } catch (error) {
    console.error('题目导出失败:', error)
    ElMessage.error('题目导出失败')
  } finally {
    exporting.questions = false
  }
}

const exportGrades = async () => {
  if (!gradeExportOptions.examinationId) {
    ElMessage.warning('请选择考试')
    return
  }

  exporting.grades = true
  try {
    await gradingApi.exportGrades({
      examination: gradeExportOptions.examinationId,
      format: gradeExportOptions.format as 'excel' | 'csv' | 'pdf'
    })
    ElMessage.success('成绩数据导出成功')
  } catch (error) {
    console.error('成绩导出失败:', error)
    ElMessage.error('成绩导出失败')
  } finally {
    exporting.grades = false
  }
}

// 下载模板
const downloadUserTemplate = () => {
  ElMessage.info('用户导入模板下载功能开发中')
}

const downloadQuestionTemplate = () => {
  ElMessage.info('题目导入模板下载功能开发中')
}

const downloadGradeTemplate = () => {
  ElMessage.info('成绩导入模板下载功能开发中')
}

const downloadErrorLog = () => {
  ElMessage.info('错误日志下载功能开发中')
}

// 生命周期
onMounted(() => {
  fetchBaseData()
})
</script>

<style scoped lang="scss">
.import-export {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;

  h1 {
    margin: 0 0 8px 0;
    color: #303133;
  }

  p {
    margin: 0;
    color: #606266;
  }
}

.import-card,
.export-card {
  .card-header {
    display: flex;
    align-items: center;
    gap: 8px;

    h3 {
      margin: 0;
      color: #303133;
    }
  }
}

.import-content,
.export-content {
  padding: 20px;
}

.upload-area {
  margin: 20px 0;

  .upload-demo {
    width: 100%;
  }
}

.import-options {
  margin: 20px 0;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 20px;
}

.import-result {
  .result-stats {
    margin: 20px 0;
  }

  .error-details {
    margin-top: 20px;

    h4 {
      margin-bottom: 12px;
      color: #303133;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .import-export {
    padding: 12px;
  }

  .el-row {
    .el-col {
      margin-bottom: 20px;
    }
  }

  .import-options {
    .el-form {
      .el-form-item {
        margin-bottom: 16px;
      }
    }
  }

  .action-buttons {
    flex-direction: column;
  }
}
</style>